package com.gmlive.common.host.retrofit

import android.text.TextUtils
import com.gmlive.common.host.manager.HostUpdateManager
import retrofit2.Retrofit
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.util.*

/**
 * Created by ZhongJianXin
 * on 2019-10-16
 * desc
 */
class RetrofitCreateHelper {
    companion object {

        private val retrofitCache = HashMap<String, Retrofit>()

        fun <T> createApi2String(baseUrl: String, clazz: Class<T>): T {
            require(!TextUtils.isEmpty(baseUrl)) { "url empty!!" }
            return getRetrofit(baseUrl).create(clazz)
        }

        private fun getRetrofit(url: String): Retrofit {
            var retrofit: Retrofit? = null
            if (retrofitCache.containsKey(url)) {
                retrofit = retrofitCache[url]
            }
            if (retrofit == null) {
                retrofit = createRetrofit(url)
                retrofitCache.put(url, retrofit)
            }
            return retrofit
        }

        private fun createRetrofit(url: String): Retrofit {
            return createBuilder().baseUrl(url).build()
        }

        private fun createBuilder(): Retrofit.Builder = if (HostUpdateManager.ins().okHttpClient == null) {
            Retrofit.Builder()
                    .addConverterFactory(ScalarsConverterFactory.create())
        } else {
            Retrofit.Builder()
                    .client(HostUpdateManager.ins().okHttpClient)
                    .addConverterFactory(ScalarsConverterFactory.create())
        }

    }
}


